<template>
<div>
  <a href="#" @click.prevent="seeAddress" style="float: left;margin-top: -10px;text-decoration-line: none">查看已有地址</a>
  <span style="float: right">欢迎您，{{userName}}&nbsp;&nbsp;&nbsp;<a href="#" @click.prevent="getOut">退出登录</a></span>
  <h2>购物车</h2>
  <div id="box">
    <div style="margin-left: -830px">
      <input type="checkbox" v-model="isAll" @change="handleAllCheck()" style="">全选/全不选
    </div>
    <ul>
      <li v-for="(item,index) in goodsData" :key="item.id">
        <input type="checkbox" v-model="checkList" :value="item" @change="handleItemChecked">
        <div>
          <div>商品:{{item.name}}</div>
          <span style="color: red;float: left">单价:{{item.salePrice}}元</span>
        </div>
        <div>
          <button @click="item.num--" :disabled="item.num<=0">-</button>
          <span>{{item.num}}</span>
          <button @click="item.num++" >+</button>
        </div>
        <div>
          <button @click="handleDelete(index,item.id)">删除</button>
        </div>
      </li>
    </ul>
    <div>总金额:￥{{ computedSum }}元&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span><button @click="order" style="background-color: #02c75a">下单</button></span></div>
  </div>

  <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="curPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
  </el-pagination>
  <!--  地址信息弹窗-->
  <el-dialog title="查看已有地址" :visible.sync="seeVisible" >
    <el-table
        ref="filterTable"
        :data="detailAddress"
        style="width: 100%;text-align: center;margin-top: 23px"
        >
      <el-table-column
          prop="province"
          label="省份"
          width="200"
      >
      </el-table-column>
      <el-table-column
          prop="city"
          label="城市"
          width="200"
      >
      </el-table-column>
      <el-table-column
          prop="district"
          label="所属区"
          width="200"
      >
      </el-table-column>
      <el-table-column
          prop="detailedAddress"
          label="详细地址"
          width="200"
      >
      </el-table-column>
    </el-table>
    <div slot="footer" class="dialog-footer">
      <el-button @click="seeVisible = false">确  定</el-button>
      <el-button @click="addAddress">新  增</el-button>
    </div>
  </el-dialog>
  <!--  订单确认弹窗-->
  <el-dialog title="信息确认" :visible.sync="orderVisible"  @close="clearForm">
    <el-form :model="form1" :rules="rules1" ref="formref1" >
      <el-form-item label="联系电话：" :label-width="formLabelWidth" prop="orderPhone">
        <el-input v-model="form1.orderPhone" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="配送地址："  :label-width="formLabelWidth" prop="address">
        <el-select v-model="form1.address" clearable placeholder="请选择地址" v-if="haveAddress">
          <el-option
              v-for="item in detailAddress"
              :key="item.id"
              :label="item.detailedAddress"
              :value="item"
              style="width: 400px">
          </el-option>
        </el-select>
        <a href="#" @click.prevent="addAddress">添加地址</a>
      </el-form-item>
      <el-form-item label="备注：" :label-width="formLabelWidth">
        <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="form1.remark">
        </el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="orderVisible = false">取 消</el-button>
      <el-button type="primary" @click="generateOrder">确 定</el-button>
    </div>
  </el-dialog>
  <!--新增对话框-->
  <el-dialog title="地址信息"  :visible.sync="dialogFormVisible" @close="clearForm" center>
    <el-form :model="form2" :rules="rules" ref="formref2">
      <el-form-item label="省" :label-width="formLabelWidth" prop="province">
        <el-input v-model="form2.province" autocomplete="off" placeholder="请输入省名称"></el-input>
      </el-form-item>
      <el-form-item label="市" :label-width="formLabelWidth" prop="city">
        <el-input v-model="form2.city" autocomplete="off" placeholder="请输入市名称"></el-input>
      </el-form-item>
      <el-form-item label="区" :label-width="formLabelWidth" prop="district">
        <el-input v-model="form2.district" autocomplete="off" placeholder="请输入区名称"></el-input>
      </el-form-item>
      <el-form-item label="详细地址" :label-width="formLabelWidth" prop="detailedAddress">
        <el-input v-model="form2.detailedAddress" autocomplete="off" placeholder="请输入详细地址"></el-input>
      </el-form-item>
      <el-form-item label="备注：" :label-width="formLabelWidth">
      <el-input
          type="textarea"
          :rows="2"
          placeholder="请输入内容"
          v-model="form2.remark">
      </el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="ensure">确 定</el-button>
    </div>
  </el-dialog>
</div>
</template>

<script>
import filter from "@/assets/filter/filter";

export default {
  name: "shoppingCart",
  data() {
    return {
      // 表格数据
      goodsData: [],
      userName:'',
      // 当前页码
      curPage: 1,
      pageSize: 5,
      total: 0,
      shopId: 0,
      customer: '',
      isAll:false,
      checkList:[],//勾选的购物车数据
      orderVisible:false,
      formLabelWidth:'120px',
      shopName:'',
      form1:{
        orderPhone:'',
        address:'',
        remark: ''
      },
      form2:{
        id:'',
        province:'',
        city:'',
        district:'',
        detailedAddress:'',
        remark:'',
        customerId:''
      },
      detailAddress:[],
      haveAddress:true,
      dialogFormVisible:false,
      seeVisible:false,
      rules1: {
        orderPhone:[
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
        address:[
          { required: true, message: '请输入配送地址', trigger: 'blur' }
        ],
      },
      rules:{
        province:[
          { required: true, message: '请输入省名称', trigger: 'blur' }
        ],
        city:[
          { required: true, message: '请输入市名称', trigger: 'blur' }
        ],
        district:[
          { required: true, message: '请输入区名称', trigger: 'blur' }
        ],
        detailedAddress:[
          { required: true, message: '请输入详细名称', trigger: 'blur' }
        ],
      }
    }
  },
  created() {
    this.queryByPage()
    this.getAddress()
  },
  methods:{
    getOut(){
      sessionStorage.clear()
      this.$router.push('/login')
    },
    order(){
      if(this.checkList.length<=0){
        this.$message({
          type: 'error',
          message: '请选择商品!'
        });
      }else {
        for(let i=0;i<this.checkList.length;i++){
          if(this.checkList[i].num<=0){
            this.$message({
              type: 'error',
              message: '商品的数量不能为零!'
            });
            return
          }
        }
        this.orderVisible=true
      }
    },
    generateOrder(){
      this.$refs.formref1.validate(async valid=> {
        if (valid ) {
          let goodsName=''
          let goodsNum=''
          for (let i = 0; i < this.checkList.length; i++) {
            goodsName+=','+this.checkList[i].name
            goodsNum+=','+this.checkList[i].name+'='+this.checkList[i].num
          }
          let now = Date.now();
          let s = filter.formatDate(now);
          goodsName=goodsName.substring(1)
          goodsNum=goodsNum.substring(1)
          let res =await this.$axios.get('/pendingOrders/save',{
            params: {
              remark:this.form1.remark,
              orderTime:s,
              customerId:this.customer.id,
              customerName:this.customer.name,
              orderPhone:this.form1.orderPhone,
              shippingAddress:this.form1.address.detailedAddress,
              distributionArea:this.form1.address.province+','+this.form1.address.city+','+this.form1.address.district,
              goodsName:goodsName,
              goodsNum:goodsNum,
              shopName:this.shopName,
              totalPrice:this.computedSum
            }
          })
          if(res.data.code===200){
            this.$message({
              type: 'success',
              message: '下单成功!'
            });
            this.orderVisible=false
            this.$router.push('/consumer')
          }else {
            alert("操作失败")
          }
        } else {
          return false;
        }
      })
    },
    async ensure(){
      this.$refs.formref2.validate(async valid=> {
        if (valid) {
          let res =await this.$axios.get('/address/save',{
            params:this.form2
          })
          if(res.data.code===200){
            this.$router.push('/consumer')
          }else {
            alert("操作失败")
          }
        } else {
          return false;
        }
      })
    },
    editAddress(){
      this.dialogFormVisible=true
    },
    seeAddress(){
      this.seeVisible=true
    },
    handleDelete(index,id){
      // console.log(index)
      //删除datalist-靠index
      this.goodsData.splice(index,1)
      //删除checkList-靠id
      this.checkList = this.checkList.filter(item => item.id!==id)

      //同步一下状态
      this.handleItemChecked()
    },
    handleAllCheck(){
      if(this.isAll){
        this.checkList=this.goodsData//全选
      }else{
        this.checkList=[]//全不选
      }
    },
    handleItemChecked(){
      if(this.checkList.length===this.goodsData.length){
        // console.log("全选")
        this.isAll = true
      }else{
        // console.log("全不选")
        this.isAll = false
      }
    },
    handleSizeChange(val) {
      this.pageSize=val
      this.queryByPage()
    },
    //切换当前页
    handleCurrentChange(val) {
      this.curPage=val
      this.queryByPage()
    },
    async queryByPage(){
      let row = JSON.parse(sessionStorage.getItem('row'));
      let user = JSON.parse(sessionStorage.getItem('user'));
      this.customer=user
      this.userName=user.name
      this.form2.customerId=user.id
      this.shopId=row.shop.id
      this.shopName=row.shop.name
      let res=await this.$axios.get('/goods/queryPageAndShopId',{
        params:{
          shopId:this.shopId,
          curPage:this.curPage,
          pageSize: this.pageSize
        }
      })
      this.goodsData=res.data.data
      this.total = res.data.total
    },
    addAddress(){
      this.orderVisible=false
      this.seeVisible=false
      this.dialogFormVisible=true
    },
    clearForm(){
      // this.$refs.formref1.resetField()
      // this.$refs.formref2.resetField()
    },
    async getAddress(){
      let resp =await this.$axios.get('/address/queryByCustomerId?customerId='+this.customer.id);
      this.detailAddress=resp.data.data
      if(this.detailAddress.length===0){
        this.haveAddress=false
      }
    }
  },
  computed:{
    computedSum(){
      //累加计算 checkList每一项的价格*数量
      let total=0
      this.checkList.forEach(item => {
        total+=item.salePrice*item.num
      });
      return total
    },
  },

}
</script>

<style scoped>
li{
  display: flex;
  /* width: 500px; */
  justify-content: space-around;
  margin-top: 20px;
}
li img{
  width: 100px;
}
</style>